package com.qyl.sever_rpc.sever;

import com.qyl.sever_rpc.pojo.Args;
import com.qyl.sever_rpc.pojo.Constant;
import com.qyl.sever_rpc.util.SerializeUtil;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.stream.Collectors;

public class Sever {

    private static int PORT = 9000;

    public static void init(){
// Create a server socket
        try (ServerSocket server = new ServerSocket(PORT)) {
            while (true) {
                try {
                    System.out.println("start...");
                    // Wait for the next connection from a client
                    Socket client = server.accept();
                    PrintWriter response = new PrintWriter(client.getOutputStream(), true);
                    BufferedReader request = new BufferedReader(
                            new InputStreamReader(client.getInputStream()));
                    String requestData = ""; // request.readLine();
                    String line;
//////                    System.out.println(request.lines().collect(Collectors.toList()).stream());
                    while (true) {
                        line = request.readLine();
                        if(StringUtils.isBlank(line)){
                            break;
                        }
                        System.out.println("Server received message from client: " + line);
                        requestData += line;
                        // Echo the request
//                    response.println(line);
                        // Add a way to stop the application.
                    }
                Args args = SerializeUtil.getSerializeArgs(requestData);
                response.println(compute(args));
//                    response.println(requestData);
                    client.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Integer compute(Args args){
        Math math = new MathImpl();
        if(args.getFlag() == Constant.ADD){
            return math.add(args.getArg1(), args.getArg2());
        }else if(args.getFlag() == Constant.SUB){
            return math.sub(args.getArg1(), args.getArg2());
        }
        return null;
    }

    public static void main(String[] args) {
        init();
    }
}
